package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.SystemDictionaryItem;
import cn.wolfcode.crm.mapper.SystemDictionaryItemMapper;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.ISystemDictionaryItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SystemDictionaryItemServiceImpl implements ISystemDictionaryItemService {

    @Autowired
    private SystemDictionaryItemMapper systemDictionaryItemMapper;

    public void delete(Long id) {
        systemDictionaryItemMapper.deleteByPrimaryKey(id);
    }

    public void save(SystemDictionaryItem systemDictionaryItem) {
        //字典明细新增前判断 序号是否为空
        //若为null 查询数据库中该字典目录对应的所有明细序号最大值 加1 赋值给新的字典明细
        if (systemDictionaryItem.getSequence() == null) {
            int maxSequence = systemDictionaryItemMapper.
                    selectMaxSequenceByParentId(systemDictionaryItem.getParentId());
            systemDictionaryItem.setSequence(maxSequence + 1);
        }
        systemDictionaryItemMapper.insert(systemDictionaryItem);
    }

    public SystemDictionaryItem get(Long id) {
        return systemDictionaryItemMapper.selectByPrimaryKey(id);
    }

    public List<SystemDictionaryItem> listAll() {
        return systemDictionaryItemMapper.selectAll();
    }

    public void update(SystemDictionaryItem systemDictionaryItem) {
        //字典明细编辑 前判断 序号是否为空
        //若为null 查询数据库中该字典目录对应的所有明细序号最大值 加1 赋值给新的字典明细
        if (systemDictionaryItem.getSequence() == null) {
            int maxSequence = systemDictionaryItemMapper.selectMaxSequenceByParentId(systemDictionaryItem.getParentId());
            systemDictionaryItem.setSequence(maxSequence + 1);
        }
        systemDictionaryItemMapper.updateByPrimaryKey(systemDictionaryItem);
    }

    @Override
    public PageInfo<SystemDictionaryItem> query(QueryObject qo) {
        //使用分页插件 传入 当前页 每页数量 排序关键字段(默认是升序)
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), "sequence");
        List<SystemDictionaryItem> systemDictionaryItems = systemDictionaryItemMapper.query(qo);
        return new PageInfo(systemDictionaryItems);
    }

    @Override
    public List<SystemDictionaryItem> selectDicItemTitleByDicSn(String sn) {

        return systemDictionaryItemMapper.selectDicItemTitleByDicSn(sn);
    }

}
